package com.fare.taluo.web.action;




import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;

import org.apache.struts2.convention.annotation.Namespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.common.remote.ftp.FtpConfig;
import com.common.remote.ftp.FtpTransferException;
import com.common.remote.sftp.SFtpFileTransferClient;
import com.dayatang.querychannel.support.Page;
import com.fare.taluo.BaseFdcAction;
import com.fare.taluo.PageComponent;
import com.fare.taluo.application.ReportDownloadApplication;
import com.fare.taluo.vo.core.ReportDownloadQueryVo;
import com.fare.taluo.vo.core.ReportUploadInfoVO;
import com.fare.util.ReportProperties;

@Namespace("/")
@Controller("reportDownloadAction")
@Scope("prototype")
public class ReportDownloadAction extends BaseFdcAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3898774286330584353L;
	private static final Logger logger = LoggerFactory.getLogger(ReportDownloadAction.class);
	private String returnPageURL; 
	private ReportDownloadQueryVo query;
	@Resource(name="reportDownloadApplicationImpl")
	private ReportDownloadApplication reportDownloadApplication;
	private List<ReportUploadInfoVO> ruiList;
	private String status;
	
	
	
	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public ReportDownloadApplication getReportDownloadApplication() {
		return reportDownloadApplication;
	}

	public void setReportDownloadApplication(
			ReportDownloadApplication reportDownloadApplication) {
		this.reportDownloadApplication = reportDownloadApplication;
	}

	public ReportDownloadQueryVo getQuery() {
		return query;
	}

	public void setQuery(ReportDownloadQueryVo query) {
		this.query = query;
	}

	public String getReturnPageURL() {
		return returnPageURL;
	}

	public void setReturnPageURL(String returnPageURL) {
		this.returnPageURL = returnPageURL;
	}

	private PageComponent pageComponent;
	private  int currentPageNo=1;
	private int pageSize=5;
	
	public PageComponent getPageComponent() {
		return pageComponent;
	}

	public void setPageComponent(PageComponent pageComponent) {
		this.pageComponent = pageComponent;
	}

	public int getCurrentPageNo() {
		return currentPageNo;
	}

	public void setCurrentPageNo(int currentPageNo) {
		this.currentPageNo = currentPageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String input(){
		try{
			Page<ReportUploadInfoVO> page = reportDownloadApplication
					.findByPage(query,currentPageNo, pageSize);
			ruiList = page.getResult();
			if(ruiList == null || ruiList.isEmpty()&& this.status!=null && this.status.equals("query")){
				status = "empty";
			}
			pageComponent = PageComponent.getInstance(page);
		}catch (Exception e) {
			status = "selecterror";
			logger.debug("",e);
		}
		
		returnPageURL = "/fare/reportDownload.jsp";
		return "dispatcher";
	}
	
	
	public String download(){

		ReportUploadInfoVO vo=null;
		try {
			vo=reportDownloadApplication.findById(query.getId());
		
		} catch (Exception e) {}
		
		if(vo==null){
			status = "filenotfound";
		}else{
			
			InputStream is=null;
			ServletOutputStream out = null;
			SFtpFileTransferClient sftpClient=null;
			try{
				ReportProperties rp=ReportProperties.getInstance();
				//文件原名
				String fileName=vo.getName();
				//文件地址
				String src=rp.getPath()+vo.getPath();
				FtpConfig config=new FtpConfig(rp.getAddress(),rp.getPort(),rp.getUserName(),rp.getPassword());
				sftpClient=new SFtpFileTransferClient(config);
				boolean flag=false;
				try {
					flag = sftpClient.connect();
				} catch (FtpTransferException e) {}
				if(!flag){
					throw new Exception("connect sftp fail");
				}
				is=sftpClient.downloadStream(src);
				out = response.getOutputStream();
				response.reset();
				// 设置输出的格式
				response.setContentType("application/pdf;charset=UTF-8");
				if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0){
					fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
				}else{
					fileName = URLEncoder.encode(fileName, "UTF-8");//其他浏览器
				}
				response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
				// 循环取出流中的数据
				byte[] b = new byte[1024*1024];
				int len;
				while ((len = is.read(b)) > 0){
					out.write(b, 0, len);
				}
				out.flush();
			}catch(Exception e){
				
			}finally{
				try {
					if(out!=null){out.close();}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					if(is!=null){is.close();}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(sftpClient!=null){sftpClient.disconnect();}
			}
		}
		
	
		returnPageURL = "/fare/reportDownload.jsp";
		return "dispatcher";
	}


	public List<ReportUploadInfoVO> getRuiList() {
		return ruiList;
	}

	public void setRuiList(List<ReportUploadInfoVO> ruiList) {
		this.ruiList = ruiList;
	}

	
}
